// 获取应用实例
const app = getApp();
const util = require('../../utils/util.js')

Page({
    data: {
        // 分类和商品数据
        childs: [],
        // 状态数据
        activeMainCategoryIndex: 0,
        activeSubCategoryIndex: 0,
        activeMerchantIndex: 0,
        isMerchantDropdownVisible: false,
        searchKey: '',
        // 导航数据
        mainCategories: [],
        subCategories: [],
        activeMainCategory: null,
        activeSubCategory: null,
        // 商品数据
        goodsList: [],
        // 商户列表
        merchants: null,
        merchantList: [],
        // UI状态
        isLoading: false,
        showBackToTop: false,
        scrollTop: 0,
        // 防抖定时器
        searchTimer: null,
        scrollTimer: null
    },

    onLoad() {
        util.callContainerApi("/product/roundmerchant", "GET").then(res => {
            const merchantList = res.data.data
            let arr = []
            merchantList.forEach(a => {
                arr.push(a.merchantName)
            })
            this.setData({
                "merchantList": merchantList,
                "merchants": arr,
                "activeMerchantIndex": 0
            })

            wx.setStorageSync('merchantId', merchantList[0].merchantId)
            wx.setStorageSync('merchantList', merchantList)
            // 在merchantList加载完成后调用loadInitialData，并传入merchantList
            this.loadInitialData(merchantList);
        }).catch(err => {
            console.error('获取商户列表失败:', err);
            wx.showToast({
                title: '获取商户列表失败',
                icon: 'none'
            });
        });
    },

    // 页面相关事件处理函数
    onPullDownRefresh() {
        this.refreshData();
    },

    // 数据加载函数 - 最终优化版
    async loadInitialData(merchantList) {
        this.setData({
            isLoading: true
        });
        const {
            activeMerchantIndex
        } = this.data;

        try {
            await util.callContainerApi(`/product/tree?merchantId=${merchantList[activeMerchantIndex].merchantId}`,"GET",null)
            .then(res => {
                const childs = res.data.data.childs || [];

                // 直接使用childs作为主分类
                const mainCategories = childs;
                // 提取所有商品
                const goodsList = this.extractAllGoods(childs);
                

                // 存储childs数据到本地
                wx.setStorageSync('childsData', childs);

                this.setData({
                    childs,
                    mainCategories,
                    goodsList,
                    isLoading: false,
                    activeMainCategoryIndex: 0,
                    activeSubCategoryIndex: 0
                }, () => {
                    // 设置默认子分类
                    if (childs.length > 0 && childs[0].childs) {
                        const subCategories = childs[0].childs.map(item => ({
                            id: item.id,
                            name: item.name
                        }));
                        this.setData({
                            subCategories
                        });
                    }
                    // 主动触发商品过滤
                    this.filterGoods();
                });
            })
        } catch (error) {
            console.error('加载数据失败:', error);
            wx.showToast({
                title: '加载失败，请重试',
                icon: 'none'
            });
            this.setData({
                isLoading: false
            });
        }
    },

    selectMerchant(e) {
        const index = e.currentTarget.dataset.index;
        if (this.data.activeMerchantIndex === index) {
            return;
        }
        const{merchantList} = this.data
        wx.showModal({
            title: '切换商城会导致购物车清空',
            complete: (res) => {
                if (res.cancel) {
                    return
                }
                if (res.confirm) {
                    // 重置分类数据
                    this.setData({
                        activeMerchantIndex: index,
                        isMerchantDropdownVisible: false,
                        subCategories: [],
                        activeMainCategoryIndex: 0,
                        activeSubCategoryIndex: 0
                    });

                    // 清空购物车
                    wx.setStorageSync('cartList', [])

                    // 修改全局商户id
                    wx.setStorageSync('merchantId', merchantList[index].merchantId)

                    // 重新加载数据
                    this.loadInitialData(merchantList);
                }
            }
        })


    },

    /* 从childs数据中提取所有商品
     */
    extractAllGoods(categories) {
        let goods = [];

        // 迭代提取商品，处理可能的null值
        for (let category of categories || []) {
            if (!category || !category.childs) continue;
            
            for (let subCategory of category.childs || []) {
            if (!subCategory || !subCategory.childs) continue;
            
            for (let item of subCategory.childs || []) {
                if (!item) continue;
                
                // 安全地获取规格信息
                const specifications = item.specifications || [];
                const spec = specifications[0] || {};
                
                // 构建商品对象
                goods.push({
                id: item.id,
                name: item.name,
                desc: item.desc || '',
                image: item.wxFileId || '',
                price: spec.price || 0,
                spec: spec.spec || '份',
                specId: spec.specId,
                pictures: item.pictures || [],
                specList: specifications,
                // 记录分类ID用于快速过滤
                categoryId: category.id,
                subCategoryId: subCategory.id
                });
            }
            }
        }
        
        wx.setStorageSync('goodList', goods);
        return goods;
    },

    async refreshData() {
        try {
            // 获取当前商户数据并传递给loadInitialData
            const {
                merchantList,
                activeMerchantIndex
            } = this.data;
            await this.loadInitialData(merchantList);
        } catch (error) {
            console.error('刷新数据失败:', error);
            wx.showToast({
                title: '刷新失败',
                icon: 'none'
            });
        } finally {
            wx.stopPullDownRefresh();
        }
    },

    // 分类切换函数
    changeMainCategory(e) {
        const index = e.currentTarget.dataset.index;
        if (index === this.data.activeMainCategoryIndex) return;

        let subCategories = [];

        if (this.data.childs[index]) {
            subCategories = this.data.childs[index].childs.map(item => ({
                id: item.id,
                name: item.name
            }));
        }

        this.setData({
            activeMainCategoryIndex: index,
            activeSubCategoryIndex: 0,
            subCategories: subCategories
        });

        this.filterGoods();
    },

    changeSubCategory(e) {
        const index = e.currentTarget.dataset.index;
        if (index === this.data.activeSubCategoryIndex) return;

        this.setData({
            activeSubCategoryIndex: index
        });
        this.filterGoods();
    },

    // 商户选择相关函数
    toggleMerchantDropdown() {
        this.setData({
            isMerchantDropdownVisible: !this.data.isMerchantDropdownVisible
        });
    },

    // 搜索相关函数
    onSearchInput(e) {
        const searchKey = e.detail.value;
        this.setData({
            searchKey
        });

        if (this.data.searchTimer) {
            clearTimeout(this.data.searchTimer);
        }

        const timer = setTimeout(() => {
            this.filterGoods();
        }, 500);

        this.setData({
            searchTimer: timer
        });
    },

    onSearch() {
        if (this.data.searchTimer) {
            clearTimeout(this.data.searchTimer);
        }
        this.filterGoods();
    },

    // 商品过滤函数
    filterGoods() {
        const filteredGoods = this.filterGoodsList(this.data.goodsList);
        this.setData({
            filteredGoods
        });
    },

    filterGoodsList(goodsList) {
        const {
            activeSubCategoryIndex,
            subCategories,
            searchKey
        } = this.data;

        // 如果有搜索关键词，只按搜索词过滤
        if (searchKey) {
            return goodsList.filter(item => 
                item.name.toLowerCase().includes(searchKey.toLowerCase())
            );
        }

        // 否则按分类过滤
        return goodsList.filter(item => {
            const subCategory = subCategories[activeSubCategoryIndex];
            if(subCategory == undefined){
                return false
            }
            if (item.subCategoryId === subCategory.id) {
                return true;
            }
            return false;
        });
    },

    // 清除搜索
    clearSearch() {
        this.setData({
            searchKey: ''
        }, () => {
            this.filterGoods();
        });
    },

    // 跳转到商品详情
    goToGoodsDetail(e) {
        const id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/goodsDetail/goodsDetail?id=${id}`
        });
    },
    addToCart(e) {
        // 防抖处理
        if (this.addToCartLock) return;
        this.addToCartLock = true;

        const id = e.currentTarget.dataset.id;
        const goods = this.data.goodsList.find(item => item.id === id);
        if (!goods) {
            this.addToCartLock = false;
            return;
        }

        try {
            // 获取购物车数据
            let cartList = wx.getStorageSync('cartList') || [];

            // 检查是否已存在
            const cartItemId = `${goods.id}_${goods.specId}`;
            const index = cartList.findIndex(item => item.cartItemId === cartItemId);
            if (index > -1) {
                // 确保num和price是数字类型
                cartList[index].num = Number(cartList[index].num || 1) + 1;
                cartList[index].price = Number(cartList[index].price || goods.price);
                // 移除可能存在的旧count字段
                if ('count' in cartList[index]) {
                    delete cartList[index].count;
                }
            } else {
                cartList.push({
                    ...goods,
                    merchandiseId: goods.id,
                    merchandiseName: goods.name,
                    cartItemId,
                    num: 1,
                    price: Number(goods.price) || 0, // 确保价格是数字
                    specDesc: goods.spec,
                    specId: goods.specId,
                    checked: false
                });
            }

            // 更新购物车
            wx.setStorageSync('cartList', cartList);

            // 显示动画效果
            this.animateAddToCart(e.currentTarget);

            // 更新购物车徽标
            util.updateCartBadge();

            wx.showToast({
                title: '已加入购物车',
                icon: 'success'
            });
        } catch (error) {
            console.error('添加购物车失败:', error);
            wx.showToast({
                title: '添加失败',
                icon: 'none'
            });
        } finally {
            this.addToCartLock = false;
        }
    },

    // 添加购物车动画
    animateAddToCart(target) {
        const query = wx.createSelectorQuery().in(this);
        query.select('.add-to-cart').boundingClientRect();
        query.select('#cart-icon').boundingClientRect();
        query.exec(res => {
            if (res[0] && res[1]) {
                const animation = wx.createAnimation({
                    duration: 800,
                    timingFunction: 'ease-out'
                });

                const start = res[0];
                const end = res[1];

                animation.translate(end.left - start.left, end.top - start.top)
                    .scale(0.5)
                    .opacity(0)
                    .step();

                this.setData({
                    addCartAnim: animation.export()
                });

                setTimeout(() => {
                    this.setData({
                        addCartAnim: null
                    });
                }, 800);
            }
        });
    },

    // 页面生命周期函数
    onHide() {
        if (this.data.searchTimer) {
            clearTimeout(this.data.searchTimer);
        }
    },

    onUnload() {
        if (this.data.searchTimer) {
            clearTimeout(this.data.searchTimer);
        }
    }
});